const app = getApp()
// 在页面中定义插屏广告
let interstitialAd = null
import config from "../../utils/config"

import {
	getById,
	get
} from "../../utils/db.js"

Page({
	data: {
		bookId: 0,
		bookDetail: {}, //图书详情
		audioList: [], //音频列表
		audioShow: false, //false 播放器不显示；true 播放器显示
		icon: "/images/play.png",
		appName: config.appName,
		userInfo: "", //用户信息
		page: 1,
		pageSize: 20,
		pageStack: null, //页面栈信息
	},
	async onLoad(e) {
		this.setData({
			pageStack: getCurrentPages().length
		})


		wx.showLoading({
			title: "正在加载"
		})

		this.data.bookId = e.id;
		this.getAudioList()


	},
	//获取音频列表
	async getAudioList() {
		// 获取音频列表
		var bookId = this.data.bookId
		var result = await get({
			collection: "audio",
			where: {
				bookId
			},
			skip: (this.data.page - 1) * this.data.pageSize,
			limit: this.data.pageSize,
			orderBy: {
				field: "audioName",
				sort: "asc"
			}
		}).catch(err => {
			console.error(err)
		})

		var audioList = this.data.audioList.concat(result.data)

		// 获取图书信息
		var result = await getById({
			collection: "book",
			id: bookId
		}).catch(err => {
			console.error(err)
		})

		var bookDetail = result.data

		wx.hideLoading()
		this.setData({
			bookDetail,
			audioList,
			userInfo: app.globalData.userInfo
		})
	},
	onReachBottom() {
		this.data.page += 1;
		this.getAudioList()
	},
	// 播放音频
	async play(e) {
		let {
			index
		} = e.currentTarget.dataset;
		this.setData({
			audioShow: true
		})

		var audio = this.selectComponent(".audio")
		// console.log(audio,"555");return;
		audio.playByIndex(index)
	},
	//点击查看
	preview() {
		var fileids = this.data.bookDetail.fileids;
		var current = this.data.bookDetail.fileids[0]
		wx.previewImage({
			urls: fileids,
			current

		})
	},
	//支付
	pay() {
		wx.showToast({
			title: '敬请等待...',
			icon: 'none'
		})
	},
	//页面分享
	onShareAppMessage() {
		return {
			title: this.data.bookDetail.name,
			path: "/pages/detail/detail?id=" + this.data.bookId,
			imageUrl: this.data.bookDetail.fileids[0]
		}
	},
	//分享到朋友圈
	onShareTimeline() {
		let {
			bookName,
			subName,
			_id
		} = this.data.bookDetail;
		subName == undefined ? '' : subName;
		let title = '【有声书】' + bookName + "：" + subName
		return {
			title,
			imageUrl: this.data.bookDetail.fileids[0],
			query: {
				id: _id
			}
		}
	},
	onShow() {

		if (wx.createInterstitialAd && config.isAd) {
			interstitialAd = wx.createInterstitialAd({
				adUnitId: 'adunit-c41d7d7535a297d5'
			})
			interstitialAd.onLoad(() => {})
			interstitialAd.onError((err) => {})
			interstitialAd.onClose(() => {})
		}
	},
	//隐藏播放器
	close() {
		this.setData({
			audioShow: false
		})
	},
	//播放下一个
	async next() {
		var audio = this.selectComponent("#audio")

		await this.setData({
			activeIndex: this.data.activeIndex++
		})
		audio.play()

	}


});